/**
 * @author : 乔磊磊
 * @date   : 2025/6/18 17:04
 * @Desc   :
 */
import {_decorator, Component, CCFloat, Label, Tween, tween} from "cc"

const {ccclass, property, requireComponent, menu, disallowMultiple} = _decorator

@ccclass("RollNumber")
@menu("UI/RollNumber")
@requireComponent(Label)
@disallowMultiple(true)
export class RollNumber extends Component {
    @property(CCFloat)
    duration: number = 0.2

    private _label: Label | null = null
    private _numberTarget: number = 0
    private _numTw: Tween<Component> | null = null

    //#region LIFE-CYCLE CALLBACKS:
    protected onLoad() {
        this._label = this.getComponent(Label) as Label
        this._label.string = "" + this._numberTarget
    }

    //#endregion LIFE-CYCLE CALLBACKS

    public get string(): string {
        return this._numberTarget.toString()
    }

    public get number(): number {
        return this._numberTarget
    }

    public rollToNumber(value: number, duration: number = this.duration) {
        this._numberTarget = value
        this.startRollNumber(duration)
    }

    private startRollNumber(duration: number) {
        if (this._numTw) {
            this._numTw.stop()
        }
        // @ts-ignore
        this._numTw = tween(this).to(duration, {lab: this._numberTarget})
            .start()
    }

    private get lab(): number {
        return Number(this._label!.string)
    }

    private set lab(text: number) {
        this._label!.string = "" + Math.floor(text)
    }

}
